/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.stores;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.qinyeit.serviceapp.entity.DishesStore;
import com.qinyeit.serviceapp.entity.PurchaseOrder;
import com.qinyeit.serviceapp.entity.PurchaseOrderDetail;
import com.qinyeit.serviceapp.entity.PurchaseSpec;
import com.qinyeit.serviceapp.entity.enums.PurchaseState;
import com.qinyeit.serviceapp.entity.enums.State;
import com.qinyeit.serviceapp.service.dishes.DishesStoreService;
import com.qinyeit.serviceapp.service.materials.PurchaseSpecService;
import com.qinyeit.serviceapp.service.stores.PurchaseOrderDetailService;
import com.qinyeit.serviceapp.service.stores.PurchaseOrderService;
import com.qinyeit.serviceapp.service.stores.SupplierService;
import com.qinyeit.serviceapp.service.stores.WarehouseService;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyeit.webapp.utils.SearchableUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * ClassName: PurchaseOrdersController <br/>
 * Function: purchaseOrder [采购订单] <br/>
 * date: 2018-11-08 14:00:02 <br/>
 *
 * @author liuwenjin
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/stores/purchaseOrders")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "management_purchaseOrder:read",name ="采购订单",deleteAble = false)
public class PurchaseOrdersController extends BaseManagementController{

	@Autowired
	private PurchaseOrderService purchaseOrderService;
	@Autowired
	private SupplierService supplierService;
	@Autowired
	private WarehouseService warehouseService;
	@Autowired
	private PurchaseOrderDetailService purchaseOrderDetailService;
	@Autowired
    private PurchaseSpecService purchaseSpecService;
	@Autowired
    private DishesStoreService dishesStoreService;
    //TODO include的字段,支持jsonPath
	private final String [] keys = {"id","no","supplierId","supplierName","warehouseId","warehouseName","address","amount","purchaser","purchaseTime","checker","checkTime","sendTime","acceptTime","remark","state","createAt","storeId","storeName"};
    private final String [] detailkeys = {"id","specId","no","name","spec","unit","count","price","realPrice","realCount","stockCount",
            "historyPrice","amount","remark","purchaseUnit","purchaseSpec","code"};

    @RequiresPermissions("management_purchaseOrder:show")
    @PermissionInfo(code = "management_purchaseOrder:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public ResponseResult<JSONObject> index(Searchable searchable){
        searchable = SearchableUtils.newSearchableWithMerchantFilter(searchable);
        Page<PurchaseOrder> purchaseOrderPage = purchaseOrderService.findAll(searchable);
        QyMap map = QyMap.map("purchaseOrderPage", JSONUtils.include(purchaseOrderPage,new Class[]{PurchaseState.class}, keys));
        //供应商
        initFormDate(map);
        return ok("查询成功",map);
    }

    @GetMapping("/create")
    public ResponseResult<QyMap> _new(Long id){
        QyMap map=QyMap.NEW();
        map.setv("purchaseOrder",JSONUtils.include(new PurchaseOrder(), keys));
        if(id!=null){
            map.setv("purchaseOrder",JSONUtils.include(purchaseOrderService.findById(id),new Class[]{PurchaseState.class},keys));

            //明细
            Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
            searchable.addSearchParam("order.id_eq",id);
            List<PurchaseOrderDetail> detailList = purchaseOrderDetailService.findWithSort(searchable);
            map.setv("detailList",JSONUtils.include(detailList,detailkeys));
/*
            List<QyMap> specList = Lists.newArrayList();
            QyMap item = null;
            PurchaseSpec spec = null;
            if(CollectionUtils.isNotEmpty(detailList)){
                for (PurchaseOrderDetail detail : detailList) {
                    spec = purchaseSpecService.findById(detail.getSpecId());
                    log.info("spec : {}",JSON.toJSONString(spec));
                    item = QyMap.NEW();
                    item.setv("state",spec.getMaterial().getState());
                    item.setv("label", spec.getId());
                    item.setv("no", detail.getNo());
                    item.setv("materialId",spec.getMaterial().getId());
                    item.setv("unit", detail.getUnit());
                    item.setv("nameValue", detail.getName());
                    item.setv("goodsSpec", spec.getMaterial().getGoodsSpec());
                    item.setv("purchaseSpec", spec.getName());
                    item.setv("purchaseUnit", spec.getUnit());
                    item.setv("purchasePrice", spec.getPrice());
                    item.setv("purchaseNewPrice", spec.getHistoryPrice());
                    item.setv("value", detail.getName());
                    item.setv("codes",spec.getMaterial().getCode());
                    specList.add(item);
                }
            }
            map.setv("materials",specList);*/
        }

        initFormDate(map);
        return ok("初始化成功", map);
    }

    @RequiresPermissions("management_purchaseOrder:edit")
    @PermissionInfo(code = "management_purchaseOrder:edit",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<String> create(@RequestBody JSONObject data, BindingResult bindingResult){
//        if(purchaseOrderService.exists(buildExists(null, "no", purchaseOrder.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        purchaseOrderService.saveDate(data,CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        return ok("保存成功");
    }

    @GetMapping("/{id}")
    public ResponseResult<JSONObject> show(@ModelAttribute PurchaseOrder purchaseOrder){
        return ok("查询成功", JSONUtils.include(purchaseOrder, keys));
    }

    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute PurchaseOrder purchaseOrder){
        QyMap map=QyMap.NEW();
        map.setv("purchaseOrder",JSONUtils.include(purchaseOrder, keys));
        initFormDate(map);

        return ok("查询成功",map);
    }

    @RequiresPermissions("management_purchaseOrder:update")
    @PermissionInfo(code = "management_purchaseOrder:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<String> update(@RequestBody JSONObject data,BindingResult bindingResult){
//        if(purchaseOrderService.exists(buildExists(null, "no", purchaseOrder.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }

        purchaseOrderService.saveDate(data,CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        return ok("更新成功", null);
    }

    @RequiresPermissions("management_purchaseOrder:destory")
    @PermissionInfo(code = "management_purchaseOrder:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/{id}")
    public ResponseResult<String> destory(@PathVariable Long id){
        purchaseOrderService.logicDelete(id);
        return ok("删除成功", null);
    }

    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id,Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            PurchaseOrder purchaseOrder = purchaseOrderService.findById(Long.valueOf(id));
            model.addAttribute(purchaseOrder);
        }
    }

    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap){
        //供应商
        qyMap.setv("suppliers",JSONUtils.include(supplierService.findWithSort(
                SearchableUtils.newSearchableWithMerchantFilter()),new Class[]{State.class},
                "id","no","name","fullName","balanceMode","linker","phone","address","state"));
        //仓库
        qyMap.setv("warehouses",JSONUtils.include(warehouseService.findWithSort(
                SearchableUtils.newSearchableWithMerchantFilter()),new Class[]{State.class},
                "id","no","name","state","sys"));
        //菜品库
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        List<DishesStore> storeList = dishesStoreService.findWithSort(searchable);
        qyMap.setv("storeList",JSONUtils.include(storeList,"id","name","creatorName","state","createAt","industry"));
    }

}